import { Component, OnInit, ViewChild, ViewContainerRef, ComponentRef, ComponentFactoryResolver, EventEmitter } from '@angular/core';
import { SubmitService } from "./submit.service";
import { InvestService } from "../../invest.service";
import { RemindComponent } from "../remind/remind.component";
import * as _ from 'lodash';
import { Util } from 'app/common/util';
import { TableComponent } from "../../modal/table/table.component";

@Component({
  selector: 'app-submit',
  templateUrl: './submit.component.html',
  styleUrls: ['./submit.component.scss'],
  providers: [SubmitService]
})
export class SubmitComponent implements OnInit {
  // 模版
  @ViewChild("submitTable", { read: ViewContainerRef })
  submitTable: ViewContainerRef;
  submitTableComponent: ComponentRef<TableComponent>;
  // 提醒者模版
  @ViewChild("submitRemind", { read: ViewContainerRef })
  submitRemind: ViewContainerRef;
  remindComponent: ComponentRef<RemindComponent>;
  // 操作
  public operate: any;
  //短信提醒
  public sSMSFlag: any = false;
  //邮件提醒
  public sEmailFlag: any = false;
  // 开始日期-查询条件
  public beginDate: any = '';
  // 结束日期-查询条件
  public endDate: any = '';
  // 提醒信息
  public auditOprZh: any;
  public remindBody: any = {
    auditOpr: '',
    title: '',
    content: ''
  };
  // 克隆列表数据，用于前端查询
  public cloneDataList: any = [];
  // 列表新数据
  public dataList: any = [];
  // 克隆列表新数据,用于页面数据标红对比
  public isChangeList: any = [];
  // 用于是否显示下拉框
  public isEditList: any = [];

  constructor(
    public submitService: SubmitService,
    public resolver: ComponentFactoryResolver,
    public investService: InvestService
  ) { }

  ngOnInit() {
    // 加载table
    this.showSubmitTable();
    // 克隆列表数据，用于前端查询
    this.cloneDataList = _.cloneDeep(this.dataList);
    this.defaultValue();
  }
  ngAfterViewInit() {
    let that = this;
    // 用于接收提醒者数据
    this.investService.remindData = new EventEmitter();
    this.investService.remindData.subscribe((data: any) => {
      if (data) {
        that.remindBody.auditOpr = _.cloneDeep(data.userChecked);
        that.auditOprZh = _.cloneDeep(data.displayName);
      }
    })
  }
  // 查询提交、保存并提交、撤销信息
  list() {
    let that = this;
    if (Util.dateOrder(this.beginDate, this.endDate)) {
      new Promise((resolve, reject) => {
        if (this.beginDate == '' && this.endDate == '') {
          // 开始日期、结束日期都为空
          this.dataList = [];
          this.dataList = _.cloneDeep(this.cloneDataList);
        } else if (this.beginDate != '' && this.endDate == '') {
          // 开始日期不为空、结束日期为空
          this.dataList = [];
          _.forEach(this.cloneDataList, (item, index: any) => {
            if ((index + 1) % 2 == 0 && item.sOprDate >= that.beginDate) {
              that.dataList.push(_.cloneDeep(that.cloneDataList[index - 1]));
              that.dataList.push(_.cloneDeep(that.cloneDataList[index]));
            }
          })
        } else if (this.beginDate == '' && this.endDate != '') {
          // 开始日期为空、结束日期不为空
          this.dataList = [];
          _.forEach(this.cloneDataList, (item, index: any) => {
            if ((index + 1) % 2 == 0 && item.sOprDate <= that.endDate) {
              that.dataList.push(_.cloneDeep(that.cloneDataList[index - 1]));
              that.dataList.push(_.cloneDeep(that.cloneDataList[index]));
            }
          })
        } else if (this.beginDate != '' && this.endDate != '') {
          // 开始日期、结束日期都不为空
          this.dataList = [];
          _.forEach(this.cloneDataList, (item, index: any) => {
            if ((index + 1) % 2 == 0 && item.sOprDate >= that.beginDate && item.sOprDate <= that.endDate) {
              that.dataList.push(_.cloneDeep(that.cloneDataList[index - 1]));
              that.dataList.push(_.cloneDeep(that.cloneDataList[index]));
            }
          })
        }
        resolve(resolve);
      }).then(resolve => {
        that.isChangeCheck();
      })
    } else {
      window['swal']("提示", "开始日期不能大于结束日期", "warning");
    }
  }
  // 提交/保存并提交/撤销
  saveOrSubmit(type) {
    let that = this;
    let checkedItem = [];
    _.forEach(this.submitTableComponent.instance.dataList, (item, index) => {
      if (item.isChecked) {
        // 防止删除其他操作有用属性，另起变量赋值
        let it = _.cloneDeep(item);
        // 产品内码赋值给nIxId，假设是新增，后台需要这个字段进行关联
        it.nIxId = it.nFundNo;
        delete it.sFundType;
        delete it.sFundCode;
        delete it.sFullName;
        delete it.sStatus;
        delete it.changeInitiator;
        delete it.changeDate;
        delete it.reviewer;
        delete it.auditDate;
        delete it.sOprStateZh;
        delete it.sStep;
        delete it.isChecked;
        delete it.nFundNo;
        delete it.riskAuditOpr;
        delete it.riskAuditDate;
        delete it.sStepZh;
        delete it.sFundTypeZh;
        delete it.sFlowStepZh;
        delete it.sOprZh;
        checkedItem.push(it);
      }
    })
    switch (type) {
      // 提交
      case 'submits':
        window['swal']({
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "是否确认提交?",
          html: true
        }, function (isConfirm) {
          if (isConfirm) {
            let postBody: any = {
              auditContentBean: that.remindBody,
              pmsInvestJournal: checkedItem
            }
            that.submitService.submits(postBody).subscribe(data => {
              if (data) {
                window['$']('#submit').modal('hide');
                window['swal']("成功", "提交成功", "success");
                that.investService.targetEdit.emit('refresh');
              }
            })
          }
        })
        break;
      // 保存并提交
      case 'saveSubmits':
        window['swal']({
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "是否确认提交并保存?",
          html: true
        }, function (isConfirm) {
          if (isConfirm) {
            let postBody: any = {
              auditContentBean: that.remindBody,
              pmsInvestJournal: checkedItem
            }
            that.submitService.saveSubmits(postBody).subscribe(data => {
              if (data) {
                window['$']('#submit').modal('hide');
                window['swal']("成功", "提交成功", "success");
                that.investService.targetEdit.emit('refresh');
              }
            })
          }
        })
        break;
      // 撤销
      case 'cancel':
        window['swal']({
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          closeOnConfirm: false,
          showLoaderOnConfirm: true,
          title: "提示",
          text: "是否确认撤销?",
          html: true
        }, function (isConfirm) {
          if (isConfirm) {
            let postBody: any = {
              auditContentBean: that.remindBody,
              pmsInvestJournal: checkedItem
            }
            that.submitService.cancel(postBody).subscribe(data => {
              if (data) {
                window['$']('#submit').modal('hide');
                window['swal']("成功", "撤销成功", "success");
                that.investService.targetEdit.emit('refresh');
              }
            })
          }
        })
        break;
    }
  }
  //获取默认模板接口
  defaultValue() {
    let that = this;
    let getBody: any = {
      "sButtonId": '70132@invest_scope_data_btn_i_commit'
    }
    this.submitService.defaultValue(getBody).subscribe(data => {
      if (data) {
        if (Array.isArray(data)) {
          if (data.length > 1) {
            that.auditOprZh = data[0].sContentZh;
            that.remindBody.auditOpr = data[0].sContent;
            if (data[0].sSMSFlag == 'true') {
              that.sSMSFlag = true;
            }
            if (data[0].sEmailFlag == 'true') {
              that.sEmailFlag = true;
            }
            that.remindBody.content = data[1].sContent;
            that.remindBody.title = data[1].sRemindTitle;
          }
        }
      }
    })
  }
  //设置默认接口
  setDefault() {
    let that = this;
    let postBody = _.cloneDeep(this.remindBody);
    postBody['sButtonId'] = '70132@invest_scope_data_btn_i_commit';
    postBody['sEmailFlag'] = _.cloneDeep(this.sEmailFlag);
    postBody['sEmailContent'] = _.cloneDeep(postBody.content);
    postBody['sSMSFlag'] = _.cloneDeep(this.sSMSFlag);
    postBody['sSMSContent'] = _.cloneDeep(postBody.content);
    delete postBody.content;
    if (postBody.sEmailFlag) {
      postBody.sEmailFlag = 'Y'
    } else {
      postBody.sEmailFlag = 'N'
    }
    if (postBody.sSMSFlag) {
      postBody.sSMSFlag = 'Y'
    } else {
      postBody.sSMSFlag = 'N'
    }
    console.log(postBody)
    window['swal']({
      type: "warning",
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnConfirm: false,
      showLoaderOnConfirm: true,
      title: "提示",
      text: "<div style='max-height: 200px;overflow-y: auto;'>" + "请确认是否设置默认" + "</div>",
      html: true
    },
      function (isConfirm) {
        if (isConfirm) {
          that.submitService.setDefault(postBody).subscribe(data => {
            if (data) {
              window['swal']("提示", "设置默认成功", "success");
            }

          })
        }
      });
  }
  // 关闭
  closeSubmit() {
    window['$']('#submit').modal('hide');
    window['$']('#submitRemind').modal('hide');
    this.submitTableComponent.destroy();
  }
  // 接收者列表
  showRemind() {
    if (this.remindComponent && this.remindComponent.instance) {
      this.remindComponent.destroy();
    }
    const remindComponent = this.resolver.resolveComponentFactory(RemindComponent);
    this.remindComponent = this.submitRemind.createComponent(remindComponent);
    window['$']('#submitRemind').modal('show');
  }
  // 提醒页面模版
  showSubmitTable() {
    if (this.submitTableComponent && this.submitTableComponent.instance) {
      this.submitTableComponent.destroy();
    }
    const submitTableComponent = this.resolver.resolveComponentFactory(TableComponent);
    this.submitTableComponent = this.submitTable.createComponent(submitTableComponent);
    this.submitTableComponent.instance.isShowCol1 = 'sFundCode';
    this.submitTableComponent.instance.isShowCol2 = 'sFullName';
    this.submitTableComponent.instance.isShowCol3 = 'display';
    // 数据标红对比
    this.isChangeCheck();
  }
  // 修改标红对比
  isChangeCheck() {
    let that = this;
    // 用于标红对比
    this.isChangeList = _.cloneDeep(this.dataList);
    // 用于是否显示下拉框
    that.isEditList = _.cloneDeep(this.dataList);
    new Promise((resolve, reject) => {
      _.forEach(this.dataList, (item, index: any) => {
        if (index > 0 && (index + 1) % 2 == 0) {
          // 前后条数据对比(新数据)
          _.forIn(item, (value, key) => {
            if (that.dataList[index - 1][key] == that.dataList[index][key]) {
              that.isChangeList[index][key] = false;
              that.isEditList[index][key] = 'no';
            } else {
              that.isChangeList[index][key] = true;
              that.isEditList[index][key] = 'no';
            }
          })
        } else {
          // 旧数据不做对比
          _.forIn(item, (value, key) => {
            that.isChangeList[index][key] = false;
            that.isEditList[index][key] = 'no';
          })
        }
      })
      resolve(resolve);
    }).then(resolve => {
      that.submitTableComponent.instance.isCheckedAll = false;
      that.submitTableComponent.instance.dataList = _.cloneDeep(that.dataList);
      that.submitTableComponent.instance.isChangeList = _.cloneDeep(that.isChangeList);
      that.submitTableComponent.instance.isEditList = _.cloneDeep(that.isEditList);
    })
  }
}
